<template>
  <div class="page-container">
    <el-card class="main-card">
      <div slot="header" class="card-header">
        <span>销售分析</span>
        <div class="header-operations">
          <el-date-picker
            v-model="dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd"
            :picker-options="pickerOptions"
            class="date-picker"
          >
          </el-date-picker>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button type="primary" @click="handleExport">导出报表</el-button>
        </div>
      </div>

      <!-- 图表区域 -->
      <div class="chart-section">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-card class="chart-card">
              <div slot="header" class="chart-header">
                <span>销售趋势分析</span>
                <el-radio-group v-model="trendType" size="small" @change="updateTrendChart">
                  <el-radio-button label="amount">销售额</el-radio-button>
                  <el-radio-button label="count">订单量</el-radio-button>
                </el-radio-group>
              </div>
              <div class="chart-content" ref="trendChart"></div>
            </el-card>
          </el-col>
          <el-col :span="12">
            <el-card class="chart-card">
              <div slot="header" class="chart-header">
                <span>品类销售占比</span>
                <el-radio-group v-model="categoryType" size="small" @change="updateCategoryChart">
                  <el-radio-button label="amount">按金额</el-radio-button>
                  <el-radio-button label="count">按数量</el-radio-button>
                </el-radio-group>
              </div>
              <div class="chart-content" ref="categoryChart"></div>
            </el-card>
          </el-col>
        </el-row>
      </div>
    </el-card>
  </div>
</template>

<script>
import * as echarts from 'echarts'
import { getSalesAnalysis, exportOrderReport } from '@/api/orders'

export default {
  name: 'SalesAnalysis',
  data() {
    // 获取今天的日期
    const today = new Date()
    
    // 计算默认的开始日期（今天的前7天）
    const defaultStartDate = new Date()
    defaultStartDate.setDate(today.getDate() - 7)
    
    // 格式化日期为 yyyy-MM-dd
    const formatDate = (date) => {
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      return `${year}-${month}-${day}`
    }
    
    return {
      dateRange: [formatDate(defaultStartDate), formatDate(today)],
      loading: false,
      trendType: 'amount',
      categoryType: 'amount',
      saleTrendList: [],
      categorySalesList: [],
      trendChartInstance: null,
      categoryChartInstance: null,
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() > Date.now()
        },
        onPick: ({ maxDate, minDate }) => {
          if (maxDate && !minDate) {
            // 如果选择了结束日期但没有选择开始日期
            // 限制只能选择往前7天内的日期
            this.pickerMinDate = new Date(maxDate)
            this.pickerMinDate.setDate(this.pickerMinDate.getDate() - 7)
          } else if (!maxDate && minDate) {
            // 如果选择了开始日期但没有选择结束日期
            // 限制只能选择往后7天内的日期
            this.pickerMaxDate = new Date(minDate)
            this.pickerMaxDate.setDate(this.pickerMaxDate.getDate() + 7)
          }
        },
        // 添加限制，最多选择7天
        shortcuts: [{
          text: '最近7天',
          onClick(picker) {
            const end = new Date()
            end.setTime(end.getTime() - 3600 * 1000 * 24)
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
            picker.$emit('pick', [start, end])
          }
        }]
      }
    }
  },
  watch: {
    dateRange(val) {
      if (val && val.length === 2) {
        const [start, end] = val
        const startDate = new Date(start)
        const endDate = new Date(end)
        const diffDays = Math.floor((endDate - startDate) / (24 * 60 * 60 * 1000))
        
        // 如果选择的日期范围超过7天，则重置为7天
        if (diffDays > 7) {
          this.$message.warning('日期范围最多为7天')
          const newEndDate = new Date(startDate)
          newEndDate.setDate(startDate.getDate() + 6)
          const formattedEndDate = this.formatDateToString(newEndDate)
          this.dateRange = [start, formattedEndDate]
        }
      }
    }
  },
  mounted() {
    this.fetchData()
    // 添加窗口大小变化时重绘图表
    window.addEventListener('resize', this.handleResize)
  },
  beforeDestroy() {
    // 移除事件监听
    window.removeEventListener('resize', this.handleResize)
    // 释放图表实例
    if (this.trendChartInstance) {
      this.trendChartInstance.dispose()
    }
    if (this.categoryChartInstance) {
      this.categoryChartInstance.dispose()
    }
  },
  methods: {
    formatDateToString(date) {
      const year = date.getFullYear()
      const month = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      return `${year}-${month}-${day}`
    },
    handleSearch() {
      this.fetchData()
    },
    handleExport() {
      this.exportReport()
    },
    exportReport() {
      // 获取角色信息
      const userInfoStr = localStorage.getItem('userInfo')
      let role = 'user'
      
      if (userInfoStr) {
        try {
          const userInfo = JSON.parse(userInfoStr)
          role = userInfo.role || 'user'
        } catch (error) {
          console.error('解析用户信息失败:', error)
        }
      }
      
      // 检查是否有角色信息
      if (!role) {
        this.$message.error('无法获取用户权限信息，无权导出报表')
        return
      }
      
      // 显示加载提示
      const loadingMessage = this.$message({
        message: '正在导出报表，请稍候...',
        type: 'info',
        duration: 0
      })

      // 使用API方法导出报表
      exportOrderReport()
        .then(response => {
          // 检查响应类型
          const contentType = response.type || ''
          if (!contentType.includes('sheet') && !contentType.includes('excel') && !contentType.includes('octet-stream')) {
            throw new Error('返回的不是Excel文件格式')
          }
          
          // 创建下载链接
          const url = window.URL.createObjectURL(response)
          const a = document.createElement('a')
          a.style.display = 'none'
          a.href = url
          a.download = '订单导出报表.xlsx'
          document.body.appendChild(a)
          a.click()
          
          // 清理
          setTimeout(() => {
            document.body.removeChild(a)
            window.URL.revokeObjectURL(url)
          }, 100)
          
          loadingMessage.close()
          this.$message.success('报表导出成功')
        })
        .catch(error => {
          loadingMessage.close()
          console.error('导出请求失败:', error)
          
          // 错误会由全局拦截器处理，无需在此处理
        })
    },
    fetchData() {
      if (!this.dateRange || this.dateRange.length !== 2) {
        // 如果没有选择日期，则使用默认日期范围
        const today = new Date()
        const defaultStartDate = new Date()
        defaultStartDate.setDate(today.getDate() - 7)
        
        this.dateRange = [
          this.formatDateToString(defaultStartDate),
          this.formatDateToString(today)
        ]
      }
      
      this.loading = true
      
      const params = {
        beginDate: this.dateRange[0],
        endDate: this.dateRange[1]
      }
      
      getSalesAnalysis(params)
        .then(response => {
          if (response.code === 200 && response.data) {
            this.saleTrendList = response.data.saleTrendList || []
            this.categorySalesList = response.data.categorySalesList || []
            
            this.$nextTick(() => {
              this.initCharts()
            })
          }
          // 错误会由全局拦截器处理
        })
        .catch(error => {
          console.error('获取销售分析数据失败:', error)
          // 错误会由全局拦截器处理
        })
        .finally(() => {
          this.loading = false
        })
    },
    initCharts() {
      if (this.$refs.trendChart && this.$refs.categoryChart) {
        this.initTrendChart()
        this.initCategoryChart()
      }
    },
    updateTrendChart() {
      this.initTrendChart()
    },
    updateCategoryChart() {
      this.initCategoryChart()
    },
    initTrendChart() {
      if (this.trendChartInstance) {
        this.trendChartInstance.dispose()
      }
      
      if (!this.saleTrendList || this.saleTrendList.length === 0) {
        return
      }
      
      this.trendChartInstance = echarts.init(this.$refs.trendChart)
      
      // 准备数据
      const dates = this.saleTrendList.map(item => item.date)
      const values = this.saleTrendList.map(item => 
        this.trendType === 'amount' ? item.saleAmount : item.orderCount
      )
      
      const option = {
        color: ['#ff6b00'],
        tooltip: {
          trigger: 'axis',
          formatter: (params) => {
            const data = params[0]
            return `${data.name}<br />${this.trendType === 'amount' ? '销售额: ¥' : '订单量: '}${data.value}`
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '10%',
          top: '10%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          boundaryGap: false,
          data: dates,
          axisLabel: {
            margin: 12,
            formatter: function(value) {
              // 只保留日期部分，不显示年份
              return value.substr(5); // 显示MM-DD格式
            }
          }
        },
        yAxis: {
          type: 'value',
          axisLabel: {
            formatter: this.trendType === 'amount' ? '¥{value}' : '{value}'
          }
        },
        series: [
          {
            name: this.trendType === 'amount' ? '销售额' : '订单量',
            type: 'line',
            smooth: true,
            data: values
          }
        ]
      }
      
      this.trendChartInstance.setOption(option)
    },
    initCategoryChart() {
      if (this.categoryChartInstance) {
        this.categoryChartInstance.dispose()
      }
      
      if (!this.categorySalesList || this.categorySalesList.length === 0) {
        return
      }
      
      this.categoryChartInstance = echarts.init(this.$refs.categoryChart)
      
      // 准备数据
      const pieData = this.categorySalesList.map(item => ({
        name: item.categoryName,
        value: this.categoryType === 'amount' ? item.totalAmount : item.totalQuantity
      }))
      
      const option = {
        color: ['#FF5252', '#1E88E5', '#4CAF50', '#FFC107', '#9C27B0', '#00BCD4', '#FF9800', '#E91E63', '#3F51B5', '#009688', '#795548', '#607D8B'],
        tooltip: {
          trigger: 'item',
          formatter: '{a} <br/>{b}: {c} ({d}%)'
        },
        legend: {
          orient: 'vertical',
          right: 10,
          top: 'center',
          data: this.categorySalesList.map(item => item.categoryName)
        },
        series: [
          {
            name: this.categoryType === 'amount' ? '销售额占比' : '销量占比',
            type: 'pie',
            radius: ['50%', '70%'],
            avoidLabelOverlap: false,
            label: {
              show: false
            },
            emphasis: {
              label: {
                show: true,
                fontSize: '20',
                fontWeight: 'bold'
              }
            },
            labelLine: {
              show: false
            },
            data: pieData
          }
        ]
      }
      
      this.categoryChartInstance.setOption(option)
    },
    handleResize() {
      if (this.trendChartInstance) {
        this.trendChartInstance.resize()
      }
      if (this.categoryChartInstance) {
        this.categoryChartInstance.resize()
      }
    }
  }
}
</script>

<style scoped>
.page-container {
  padding: 20px;
  background: #f0f2f5;
  min-height: calc(100vh - 120px);
}

.main-card {
  border-radius: 8px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: #304156;
}

.header-operations {
  display: flex;
  gap: 10px;
}

.date-picker {
  width: 350px;
}

.chart-section {
  margin: 20px 0;
}

.chart-card {
  border-radius: 8px;
}

.chart-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: #304156;
}

.chart-content {
  height: 400px;
}

/* Element UI 主题覆盖 */
:deep(.el-button--primary) {
  background-color: #ff6b00;
  border-color: #ff6b00;
}

:deep(.el-button--primary:hover),
:deep(.el-button--primary:focus) {
  background-color: #ff8533;
  border-color: #ff8533;
}

:deep(.el-radio-button__orig-radio:checked+.el-radio-button__inner) {
  background-color: #ff6b00;
  border-color: #ff6b00;
  box-shadow: -1px 0 0 0 #ff6b00;
}

:deep(.el-radio-button__inner:hover) {
  color: #ff6b00;
}
</style> 